package com.sali.netty.handler;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;

/**
 * @description:
 * @author: sali
 * @date: 2025/2/22 下午1:58.
 * @version: 1.0
 */
@Slf4j
public class MockDecoder extends LengthFieldBasedFrameDecoder {
    public MockDecoder(ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
        super(byteOrder, maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        in = (ByteBuf) super.decode(ctx, in);
        if (in == null) {
            return null;
        }
        // 改成转小端模式，需要配合buf.getUnsignedIntLE(offset);一起改动
        int length = in.readIntLE();
        if (in.readableBytes() != length) {
            log.error("标记长度不符合实际长度！！");
        }

        byte[] bytes = new byte[length];
        in.readBytes(bytes);
        String message = new String(bytes, StandardCharsets.UTF_8);
        ReferenceCountUtil.release(in);
        try {
            return JSONUtil.parseObj(message);
        } catch (JSONException e) {
            log.warn("接受客户端发送的非法数据！！ data: [{}]", message);
        }
        return null;
    }

}
